_package("alz.util");

/**
 * 链接(URL)解析类
 * Creates an URLParser instance
 * @param {String} url The url to parse
 * @return {Object} return an URLParser object
 * @exception {String} Throws an exception if the specified url is invalid
 */
_class("URLParser", "", function(){
	//this.version = 0.1;
	this._regex = /^((\w+):\/\/)?((\w+):?(\w+)?@)?([^\/\?:]+):?(\d+)?(\/?[^\?#]+)?\??([^#]+)?#?(\w*)/;
	this._fields = {
		"username"   : 4,
		"password"   : 5,
		"port"       : 7,
		"protocol"   : 2,
		"host"       : 6,
		"pathname"   : 8,
		"url"        : 0,
		"querystring": 9,
		"fragment"   : 10
	};
	for(var f in this._fields){
		var k = f.capitalize();
		this["get" + k] = function(field){
			return function(){
				return this._values[field];
			};
		}(f);
	}
	this._init = function(url){
		this._values = {};
		if(typeof url != "undefined"){
			this._parse(url);
		}
	};
	/**
	 * @param {String} url The url to parse
	 * @exception {String} Throws an exception if the specified url is invalid
	 */
	this.setURL = function(url){
		this._parse(url);
	};
	this._initValues = function(){
		for(var f in this._fields){
			this._values[f] = "";
		}
	};
	this._parse = function(url){
		this._initValues();
		var r = this._regex.exec(url);
		if(!r) throw "[URLParser::_parse]Invalid URL";
		for(var f in this._fields){
			var key = this._fields[f];
			if(typeof r[key] != "undefined"){
				this._values[f] = r[key];
			}
		}
	};
});